package com.breadenglish.cms.api.app.gateway.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 坤.
 */
public class PhoneNumberUtil {
    public final static Pattern CHINA_MOBILE_PHONE_NUMBER = Pattern.compile("^(134|135|136|137|138|139|150|151|152|157|158|159|147|182|183|184|187|188|178)\\d{8}$");
    public final static Pattern UNICOM_PHONE_NUMBER = Pattern.compile("^(130|131|132|145|155|156|185|186|145|176)\\d{8}$");
    public final static Pattern TELCOM_PHONE_NUMBER = Pattern.compile("^(133|153|180|181|189)\\d{8}$");
    public final static Pattern CHINESE_PHONE_NUMBER = Pattern.compile("^(13|14|15|18|17)\\d{9}$");
    public final static int CHINA_MOBILE = 1;
    public final static int UNICOM = 2;
    public final static int TELCOM = 3;
    public final static int ERROR_PHONE_NUMBER = 0;

    public static boolean isMatched(String regex, String in) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(in);
        boolean isMatched = matcher.matches();
        return isMatched;
    }

    public static boolean isPhoneNumber(String pn) {
        pn = remove86(pn);
        return CHINESE_PHONE_NUMBER.matcher(pn).matches();
    }

    public static int getOperator(String pn) {
        pn = remove86(pn);
        if (CHINA_MOBILE_PHONE_NUMBER.matcher(pn).matches())
            return CHINA_MOBILE;
        else if (UNICOM_PHONE_NUMBER.matcher(pn).matches())
            return UNICOM;
        else if (TELCOM_PHONE_NUMBER.matcher(pn).matches())
            return TELCOM;
        else
            return ERROR_PHONE_NUMBER;
    }

    public static String remove86(String pn) {
        if (pn == null || pn.length() <= 11)
            return pn;
        if (pn.substring(0, 2).equals("86"))
            return pn.substring(2);
        if (pn.substring(0, 3).equals("+86"))
            return pn.substring(3);
        return pn;
    }
}
